package com.daiyang.lotterysystem.common.utils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;
import org.springframework.util.ReflectionUtils;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {
    public JacksonUtil() {

    }
    private static final ObjectMapper OBJECT_MAPPER;
    static {
        OBJECT_MAPPER = new ObjectMapper();
    }

    //实现一个单例模式
    private static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }
    private static <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JacksonException.class);
    }
    //根据springframework的JsonParseException改写,避免频繁的try catch
    // 参考org.springframework.boot.json.JsonParser的实现
    // 参考org.springframework.boot.json.JsonParser的实现
    private static <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        }
        catch (Exception ex) {
            if (check.isAssignableFrom(ex.getClass())) {
                throw new JsonParseException(ex);
            }
            throw new IllegalStateException(ex);
        }
    }

    /**
     * 序列化对象为json字符串
     * @param value
     * @return
     */
    public static String writeValueAsString(Object value) {
        return tryParse(()->{
            return JacksonUtil.getObjectMapper().writeValueAsString(value);
        });
    }

    /**
     * 反序列化json字符串为对象
     * @param json
     * @param type
     * @return
     */
    public static <T> T readValue(String json,Class<T> type) {
        return tryParse(()->{
           return JacksonUtil.getObjectMapper().readValue(json,type);
        });
    }

    /**
     * 反序列化json字符串为List
     */
    public static <T> T   readListValue(String json, Class<?> paramClasses) {
        JavaType javaType = JacksonUtil.getObjectMapper().getTypeFactory()
                .constructParametricType(List.class,paramClasses);
        return tryParse(()->{
            return JacksonUtil.getObjectMapper().readValue(json, javaType);
        });

    }

}
